<template>
    <div class="app-container">
        <div v-if="!userStore.isMobile" style="margin-bottom: 10px;">
            <el-tag type="primary" size="large"
                style="">提示：标黄的行表示在对应的管家婆项目出库单中未查找到该设备的相关出库单，请点击修改手动关联管家婆出库单中实际出库的设备</el-tag>
        </div>


        <!-- 搜索框 -->
        <el-input :style="{
            width: userStore.isMobile ? '100%' : '400px',
            marginBottom: userStore.isMobile ? '10px' : '15px'
        }" :size="userStore.isMobile ? 'large' : 'default'" v-model="searchKeyword"
            placeholder="支持输入设备名称、型号、参数、数量、备注编码搜索" clearable />


        <el-table :row-class-name="tableRowClassName" height="70vh" :summary-method="getSummaries" border show-summary
            style="padding: 0px;margin: 0px;" v-loading="loading" :data="filteredSaleList"
            @selection-change="handleSelectionChange">


            <el-table-column label="名称" width="220" align="center" prop="name" />
            <el-table-column label="设备型号" width="220" align="center" prop="model" />
            <el-table-column label="设备参数" show-overflow-tooltip width="220" align="center" prop="param" />
            <el-table-column label="品牌" align="center" show-overflow-tooltip width="220" prop="brand" />
            <el-table-column label="数量" align="center" prop="count" />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="单价(￥)" align="center" prop="price" />
            <el-table-column label="总价(￥)" align="center" show-overflow-tooltip width="120" prop="totalPrice" />
            <el-table-column label="折扣率(%)" align="center" prop="discountRate" />
            <el-table-column label="折后价(￥)" align="center" show-overflow-tooltip width="120" prop="discountPrice" />
            <el-table-column label="备注编码" align="center" show-overflow-tooltip width="220" prop="remarkCode" />
            <el-table-column label="预数量" align="center" prop="preCount" />
            <el-table-column label="预成本(￥)" align="center" show-overflow-tooltip width="120" prop="prePrice" />
            <el-table-column label="预单价成本(￥)" show-overflow-tooltip width="120" align="center" prop="preUnit" />
            <el-table-column label="操作人" align="center" prop="operator" />
            <el-table-column label="操作" fixed="right" :width="userStore.isMobile ? 80 : 120" align="center"
                class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog :title="title" v-model="open" :width="userStore.isMobile ? '95%' : '600px'" append-to-body>
            <el-form ref="costingRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="名称" prop="name">
                    <el-input :disabled="true" v-model="form.name" placeholder="" />
                </el-form-item>

                <el-form-item label="型号" prop="model">
                    <el-input :disabled="true" v-model="form.model" placeholder="" />
                </el-form-item>

                <el-form-item label="设备参数" prop="param">
                    <el-input :disabled="true" v-model="form.param" placeholder="" />
                </el-form-item>

                <el-form-item label="数量" prop="count">
                    <el-input :disabled="true" v-model="form.count" placeholder="" />
                </el-form-item>

                <el-form-item label="备注编码" prop="housekeeperProject">
                    <el-select @change="setRemarkCode" clearable v-model="form.goodsId" filterable
                        placeholder="请选择或输入关键字查找" style="width: 580px">
                        <el-option v-for="item in saleList" :key="item.goodsId" :label="item.goodsAllName"
                            :value="item.goodsId" />
                    </el-select>
                </el-form-item>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Costing">
import { listCosting, getCosting, delCosting, addCosting, updateCosting } from "@/api/project/costing";
import { listSale, getSale, delSale, addSale, updateSale, gjpListSale, gjpAllListSale } from "@/api/project/sale";
import { Bell } from '@element-plus/icons-vue'

import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

const props = defineProps({
    datas: {
        type: Object, // 指定类型为对象
        required: true, // 是否必填
    },
    column: {
        type: Number, // 指定类型为数字
        default: 3, // 设置默认值为 3
    },
    sizes: {
        default: 'default',
    },
    personList: {
        default: [],
    },
    payList: {
        default: [],
    },
    attachmentList: {
        default: [],
    },
    implementList: {
        default: [],
    },
    warrantyList: {
        default: [],
    },
    accountingList: {
        default: [],
    },


    isView: {
        default: false,
    },


});
const { datas, column, sizes, personList, payList, attachmentList, implementList, accountingList, warrantyList, isView } = toRefs(props);

const { proxy } = getCurrentInstance();

const costingList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const saleList = ref([]);

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 1000,
        name: null,
        model: null,
        param: null,
        brand: null,
        count: null,
        unit: null,
        price: null,
        totalPrice: null,
        discountRate: null,
        discountPrice: null,
        remarkCode: null,
        preCount: null,
        prePrice: null,
        preUnit: null,
        finalCount: null,
        finalCost: null,
        loginIp: null,
        loginDate: null,
        projectNo: null,
        goodsId: null
    },
    rules: {
        id: [
            { required: true, message: "id不能为空", trigger: "blur" }
        ],
    }
});

const { queryParams, form, rules } = toRefs(data);

const searchKeyword = ref('');


// 计算属性过滤数据
const filteredSaleList = computed(() => {
    console.log("costingList.value", costingList.value);

    const keyword = searchKeyword.value.trim().toLowerCase();
    if (!keyword) {
        return costingList.value;
    }

    return costingList.value.filter(item =>
        [item.remarkCode, item.name, item.model, item.param, item.count].some(field =>
            field != null && String(field).toLowerCase().includes(keyword)
        )
    );
});





/** 查询正式清单的商品列表 */
function getList() {

    if (datas.value.projectNo == undefined || datas.value.projectNo == null || datas.value.projectNo == '') {
        return
    }

    loading.value = true;
    queryParams.value.projectNo = datas.value.projectNo
    console.log("请求上传数据", queryParams.value);

    listCosting(queryParams.value).then(response => {
        costingList.value = response.data.rows;
        total.value = response.data.total;
        loading.value = false;
    }).finally(() => {
        loading.value = false;
    });

}


// 行样式方法
const tableRowClassName = ({ row }) => {
    return row.status == 1 ? 'warning-row' : '';
};


// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        name: null,
        model: null,
        param: null,
        brand: null,
        count: null,
        unit: null,
        price: null,
        totalPrice: null,
        discountRate: null,
        discountPrice: null,
        remarkCode: null,
        preCount: null,
        prePrice: null,
        preUnit: null,
        finalCount: null,
        finalCost: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        loginIp: null,
        loginDate: null,
        projectNo: null
    };
    proxy.resetForm("costingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加正式清单的商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    let params = {
        housekeeperProject: datas.value.housekeeperProject
    }

    if (!params.housekeeperProject) {
        proxy.$modal.msgError("未关联管家婆项目,请关联");
        loading.value = false;
        return
    }
    console.log("params.housekeeperProject", params.housekeeperProject);

    gjpAllListSale(params).then(response => {
        console.log('所有出库单', response);
        saleList.value = response.data.reduce((acc, current) => {
            if (!acc.some(item => item.goodsId === current.goodsId)) {
                acc.push(current);
            }
            return acc;
        }, []);


    });


    const _id = row.id || ids.value
    getCosting(_id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "选择实际对应的出库数据";
    });


}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["costingRef"].validate(valid => {
        if (valid) {
            if (form.value.id != null) {
                updateCosting(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addCosting(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除正式清单的商品编号为"' + _ids + '"的数据项？').then(function () {
        return delCosting(_ids);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}


function getSummaries(param) {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = `合计（共 ${data.length} 条）`;
            return;
        }

        const prop = column.property;

        // 需要统计的列配置
        const statsColumns = {
            totalPrice: { name: '总价', format: 'money' },
            discountPrice: { name: '折后价', format: 'money' },
            prePrice: { name: '预成本', format: 'money' },
            count: { name: '数量', format: 'int' }
        };

        if (statsColumns[prop]) {
            const values = data.map(item => Number(item[prop]));
            if (!values.every(value => isNaN(value))) {
                const sum = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    return isNaN(value) ? prev : prev + value;
                }, 0);

                // 格式化输出
                switch (statsColumns[prop].format) {
                    case 'int':
                        sums[index] = Math.round(sum).toString(); // 四舍五入取整，转为字符串
                        break;
                    case 'money':
                        sums[index] = '￥ ' + sum.toFixed(2); // 四舍五入保留两位小数并添加货币符号
                        break;
                    default:
                        sums[index] = sum.toString();
                }
            } else {
                sums[index] = 'N/A';
            }
        } else {
            sums[index] = '';
        }
    });

    return sums;
}


// function getSummaries(param) {
//     const { columns, data } = param;
//     const sums = [];
//     columns.forEach((column, index) => {
//         if (index === 0) {
//             sums[index] = `合计（共 ${data.length} 条）`;
//             return;
//         }

//         const prop = column.property;

//         // 需要统计的列配置
//         const statsColumns = {
//             totalPrice: { name: '总价', format: 'money' },
//             discountPrice: { name: '折后价', format: 'money' },
//             prePrice: { name: '预成本', format: 'money' },
//             count: { name: '数量', format: 'int' }
//         };

//         if (statsColumns[prop]) {
//             const values = data.map(item => Number(item[prop]));
//             if (!values.every(value => isNaN(value))) {
//                 const sum = values.reduce((prev, curr) => {
//                     const value = Number(curr);
//                     return isNaN(value) ? prev : prev + value;
//                 }, 0);

//                 // 格式化输出
//                 switch (statsColumns[prop].format) {
//                     case 'int':
//                         sums[index] = Math.round(sum);
//                         break;
//                     case 'money':
//                         sums[index] = sum.toFixed(2);
//                         break;
//                     default:
//                         sums[index] = sum;
//                 }
//                 sums[index] = "￥ " + sums[index]
//             } else {
//                 sums[index] = 'N/A';
//             }
//         } else {
//             sums[index] = '';
//         }
//     });

//     return sums;
// }


const setRemarkCode = (id) => {
    if (id == undefined) {
        form.value.remarkCode = '';
        return
    }
    const filteredObjects = saleList.value.find((obj) => obj.goodsId == id);
    form.value.remarkCode = '';
    console.log("filteredObjects", filteredObjects);
    form.value.remarkCode = filteredObjects?.goodsAllName || '';
    console.log("setHousekeeperName", form.value.remarkCode);
    console.log("关联的goodsid", form.value);


}


onMounted(() => {
    // nextTick(() => {
    console.log("当前子组件666", datas);
    getList()
    // })
})
</script>


<style scoped>
:deep(.el-table .warning-row) {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

/* 悬停效果 */
:deep(.el-table .warning-row:hover td) {
    --el-table-tr-bg-color: var(--el-color-warning-light-8);
    background-color: var(--el-table-tr-bg-color);
}

/* 如果需要更醒目的边框样式 */
:deep(.el-table .warning-row td) {
    border-bottom: 1px solid var(--el-color-warning-light-5);
    border-top: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .warning-row td:first-child) {
    border-left: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .warning-row td:last-child) {
    border-right: 1px solid var(--el-color-warning-light-5);
}
</style>